﻿import { AfterViewInit, Component, Injector, ViewEncapsulation , ViewChild} from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { EntityDtoOfInt64, UserListDto, WorkflowServiceProxy, UserServiceProxy, OrganizationUnitServiceProxy, WorkflowStatus,  GetWorkflowInstanceViewDto} from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import * as _ from 'lodash';
import * as moment from 'moment';




@Component({
    templateUrl: './poccess.component.html',
    styleUrls: ['./poccess.component.less'],
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class PoccessComponent extends AppComponentBase implements AfterViewInit {
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;

    getWorkflowInstancePoccessViewDtos: GetWorkflowInstanceViewDto[];
    filterText = '';
    constructor(
        injector: Injector ,
        private _workflowServiceProxy: WorkflowServiceProxy,
        private _userServiceProxy: UserServiceProxy
    ) {
        super(injector);
    }



    getPoccessWorkflow(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }

        this.primengTableHelper.showLoadingIndicator();

        this._workflowServiceProxy.getWorkflowIdsOfOwnProssessor(
            this.filterText,
            this.primengTableHelper.getSorting(this.dataTable),
            this.primengTableHelper.getMaxResultCount(this.paginator, event),
            this.primengTableHelper.getSkipCount(this.paginator, event),
            []
        ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
        .subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            //this.primengTableHelper.records = result.items;
            this.getWorkflowInstancePoccessViewDtos = result.items;
            this.primengTableHelper.hideLoadingIndicator();

             _.forEach(this.getWorkflowInstancePoccessViewDtos, viewItem => {

                this._workflowServiceProxy.getExecutionPointer(viewItem.id)
                .subscribe(pointResult => {
                    let currentD = this.getWorkflowInstancePoccessViewDtos.find((element) => (element.id === viewItem.id));
                    currentD.currentStepId =  pointResult[0].id;
                    currentD.currentStepTime =  pointResult[0].startTime;
                    currentD.receivedStepTimeInterval = this.dateDifference(pointResult[0].startTime);
                });

                this._workflowServiceProxy.getOpenUserActions(viewItem.id)
                .subscribe(actionResult => {
                    let currentD = this.getWorkflowInstancePoccessViewDtos.find((element) => (element.id === viewItem.id));
                    currentD.currentStepName =  actionResult[0].prompt;
                    currentD.currentStepUserId =  actionResult[0].assignedPrincipal;

                    this._userServiceProxy.getUserForAll(currentD.currentStepUserId)
                    .subscribe(userResult => {
                        let currentD = this.getWorkflowInstancePoccessViewDtos.find((element) => (element.id === viewItem.id));
                        currentD.currentStepUserName =  userResult.user.name;
                        currentD.currentStepUserOuName = userResult.allOrganizationUnits[0].displayName;
                    });
                });
            }); 
        });
    }

    ngAfterViewInit(): void {

    }

    dateDifference(actualDate): string {
        // Calculate time between two dates:
        const date1 = actualDate; // the date you already commented/ posted
        const date2: any = new Date(); // today

        let r = {}; // object for clarity
        let message: string;

        const diffInSeconds = Math.abs(date2 - date1) / 1000;
        const days = Math.floor(diffInSeconds / 60 / 60 / 24);
        const hours = Math.floor(diffInSeconds / 60 / 60 % 24);
        const minutes = Math.floor(diffInSeconds / 60 % 60);
        const seconds = Math.floor(diffInSeconds % 60);
        const milliseconds = Math.round((diffInSeconds - Math.floor(diffInSeconds)) * 1000);

        const months = Math.floor(days / 31);
        const years = Math.floor(months / 12);

        // the below object is just optional
        // if you want to return an object instead of a message
        r = {
            years: years,
            months: months,
            days: days,
            hours: hours,
            minutes: minutes,
            seconds: seconds,
            milliseconds: milliseconds
        };

        // check if difference is in years or months
        if (years === 0 && months === 0) {
            // show in days if no years / months
            if (days > 0) {
                if (days === 1) {
                    message = days + ' 天';
                } else { message = days + ' 天'; }
            }  else if (hours > 0) {
                if (hours === 1) {
                    message = hours + ' 小时';
                } else {
                    message = hours + ' 小时';
                }
            } else {
                // show in minutes if no years / months / days
                if (minutes === 1) {
                    message = minutes + ' 分钟';
                } else {
                    message = minutes + ' 分钟';
                }
            }
        } else if (years === 0 && months > 0) {
            // show in months if no years
            if (months === 1) {
                message = months + ' 月';
            } else {
                message = months + ' 月';
            }
        } else if (years > 0) {
            // show in years if years exist
            if (years === 1) {
                message = years + ' 年';
            } else {
                message = years + ' 年';
            }
        }

        return message + ' 前';
 // this is the message a user see in the view
    }
}
